/*
 * Copyright (c) 2021 柯华栋
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gio/gio.h>
#include <stdio.h>

static pthread_mutex_t mutex;
static pthread_mutexattr_t attr;

void ipc_init(void)
{
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(&mutex, &attr);
}

void ipc_lock(void)
{
	pthread_mutex_lock(&mutex);
}

void ipc_unlock(void)
{
	pthread_mutex_unlock(&mutex);
}


int sum(int num)
{
	ipc_lock();	
	printf("num = %d\n", num);
	usleep(100*1000);
	
	if (num == 0) {
		ipc_unlock();
		return 0;
	}	
	int s = num + sum(num-1);
	ipc_unlock();
	return s;
}

static void* test_async_func(void *arg)
{
	(void)arg;
	
	printf("sum of 10 = %d\n", sum(10));
	
    return NULL;
}

// 异步调用
static void test_async(void)
{
	pthread_t t;
	
}

int main()
{
	ipc_init();
	
	pthread_t t[10];
	for (int i = 0; i < 10; i++)
		pthread_create(&t[i], NULL, test_async_func, NULL);
	
	for (int i = 0; i < 10; i++)
		pthread_join(t[i], NULL);
}
